package org.flycloud.web.decoupling;

import java.lang.reflect.Proxy;

import javax.annotation.PostConstruct;

import org.flycloud.web.decoupling.annotation.RemoteController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class RemoteControllerFactory {

	@Autowired
	private Environment env;

	private static RemoteControllerFactory factory;

	public Object createInstance(Class<?> cls) {
		RemoteController rc = cls.getAnnotationsByType(RemoteController.class)[0];
		String point = env.getProperty(rc.value());
		ControllerProxy invocationHandler = new ControllerProxy(point, cls);
		Object newProxyInstance = Proxy.newProxyInstance(cls.getClassLoader(), new Class[] { cls }, invocationHandler);
		return (Object) newProxyInstance;
	}

	@PostConstruct
	public void init() {
		factory = this;
	}
	
	public static Object getInstance(Class<?> cls) {
		return factory.createInstance(cls);
	}

}